package com.l.web.master.system.config;

import org.l.qiao.Cluster;
import org.l.qiao.Page;
import org.l.qiao.builder.Field;
import org.l.qiao.builder.Query;
import org.l.qiao.builder.Update;
import org.l.qiao.util.JsonUtils;
import org.l.qiao.web.KeyUpdate;
import com.l.web.common.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ConfigService {

    @Autowired
    private ConfigDAO configDAO;

    public ConfigService() {
    }

    public List<Cluster> getPageList(Page page) {
        Config config = new Config();
        Field field = new Field();
        Query query = new Query();
        field.exclude(config.OPTION);
        List<Cluster> list = configDAO.findPage(query, field, null, page);
        return list;
    }

    public Config getDetail(String id) {
        Cluster cluster = configDAO.findById(id);
        return new Config(cluster);
    }

    public int save(Config config) {
        String id = config.setId();
        config.put(Config.CREATED, new Date());
        configDAO.insert(config);
        return ResponseCode.FINISH;
    }

    public long update(KeyUpdate keyUpdate) throws Exception {
        long result;

        if ("OPTION".equals(keyUpdate.getName())) {
            result = updateOption(keyUpdate);
        } else {
            result = configDAO.update(keyUpdate);
        }
        return result;
    }

    private long updateOption(KeyUpdate keyUpdate) throws NoSuchFieldException, IllegalAccessException {
        long result;
        Map map = JsonUtils.toMap(keyUpdate.getValue());
        Query query = new Query();
        query.setId(keyUpdate.getId());
        Update update = new Update();
        update.put(keyUpdate.getName(), map);
        result = configDAO.updateSetOne(query, update);
        return result;
    }

    public int remove(List<String> ids) {
        Query query = new Query();
        query.idIn(ids);
        configDAO.remove(query);
        return ResponseCode.FINISH;
    }

    public Config getConfig(String key) {
        Query query = new Query();
        query.eq(Config.KEY, key);
        Cluster config = configDAO.findOne(query);

        if (config != null) {
            return new Config(config);
        } else {
            return null;
        }
    }
}
